package com.xh.bussiness.jingyou.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xh.bussiness.jingyou.bean.request.JYPaperDownRequest;
import com.xh.bussiness.jingyou.bean.request.JYPaperQueryRequest;
import com.xh.bussiness.jingyou.bean.request.JYPaperSaveRequest;
import com.xh.bussiness.jingyou.bean.request.JYSmartPaperSaveRequest;
import com.xh.bussiness.jingyou.constants.JingYouConstants;
import com.xh.bussiness.jingyou.service.IJYAuthService;
import com.xh.bussiness.jingyou.service.IJYPaperService;
import com.xh.bussiness.jingyou.service.IJYQuestionService;
import com.xh.bussiness.jingyou.utils.Utility;
import com.xh.bussiness.tiku.bean.dto.PaperChapterDto;
import com.xh.bussiness.tiku.bean.dto.PaperDto;
import com.xh.bussiness.tiku.bean.dto.PaperQuestionDto;
import com.xh.bussiness.tiku.bean.dto.QuestionDto;
import com.xh.bussiness.tiku.bean.request.PaperChapterSaveRequest;
import com.xh.bussiness.tiku.bean.request.PaperSaveRequest;
import com.xh.bussiness.tiku.service.IPaperService;
import com.xh.core.bean.XhPage;
import com.xh.core.util.DateUtils;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务类
 * </p>
 *
 * @author JQM
 * @since 2019-11-11
 */
@Service
public class JYPaperServiceImpl implements IJYPaperService{
	
	@Autowired
	private IJYAuthService authService;
	@Autowired
	private IJYQuestionService questionService;
	/**
	 * 智能组卷
	 * @return
	 * @throws Exception 
	 */
	@Override
	public PaperDto smartPaper(JYSmartPaperSaveRequest paper) throws Exception{
		// 检查数量
		String url = String.format("http://api.jyeoo.com/v1/%s/paper2?tp=1&id=&title=%s",
				paper.getSubjectId(),URLEncoder.encode(paper.getTitle(), "UTF-8"),1,5);
		String token = authService.getToken(JingYouConstants.INTERFACE_TYPE_PAPER_SMART_PAPER, JingYouConstants.INTERFACE_LIMIT_PAPER_SMART_PAPER);
		JSONObject json = Utility.sendPost(token, url, paper.getFilters(), JSONObject.class);
        System.out.println(JSON.toJSONString(json));
        PaperDto paperDto = json2Paper(json);
        BeanUtils.copyProperties(paper, paperDto);

        return paperDto;
    }
	/**
	 * 挑题组卷
	 * @param paper
	 * @return
	 * @throws Exception
	 */
	@Override
	public PaperDto selectQuestionPaper(JYPaperSaveRequest paper) throws Exception{

		String url = String.format("http://api.jyeoo.com/v1/%s/paper", paper.getSubject());

		String token = authService.getToken(JingYouConstants.INTERFACE_TYPE_PAPER_SUBMIT, JingYouConstants.INTERFACE_LIMIT_PAPER_SUBMIT);
		JSONObject json = Utility.sendPost(token, url, paper, JSONObject.class);
		return json2Paper(json);
	}
	/**
	 * 分页搜索试卷
	 */
	@Override
	public XhPage<PaperDto> queryByPaparm(XhPage page, JYPaperQueryRequest bean) throws Exception{

		String fd = bean.getStartTime() == null ? "" : bean.getStartTime();
		String td = bean.getEndTime() == null ? "" : bean.getEndTime();
//		String url = String.format("http://api.jyeoo.com/v1/%s/paper2?fd=%s&td=%s&pi=%s&ps=%s", bean.getSubject(), fd, td, page.getCurrent(),
//				page.getSize());
		String url = String.format("http://api.jyeoo.com/v1/%s/paper2?fd=%s&td=%s&pi=%s&ps=%s", bean.getSubject(), fd, td,page.getCurrent(),
				page.getSize());
		String token = authService.getToken(JingYouConstants.INTERFACE_TYPE_PAPER_QUERY_BY_PAGE, JingYouConstants.INTERFACE_LIMIT_PAPER_QUERY_BY_PAGE);
		JSONObject json = Utility.sendGet(token, url, JSONObject.class);
		return str2Xhpage(page,json);
	}
	/**
	 * 
	 */
	@Override
	public PaperDto queryPaper(JYPaperQueryRequest bean) throws Exception{

		String url = String.format("http://api.jyeoo.com/v1/%s/paper/%s", bean.getSubject(),bean.getId());
		
		String token = authService.getToken(JingYouConstants.INTERFACE_TYPE_PAPER_QUERY_BY_ID, JingYouConstants.INTERFACE_LIMIT_PAPER_QUERY_BY_ID);
		JSONObject json = Utility.sendGet(token, url, JSONObject.class);
		return json2Paper(json);
	}
	
	/**
	 * 
	 */
	@Override
	public byte[] downPaper(JYPaperDownRequest bean) throws Exception{

		String url = String.format("http://api.jyeoo.com/v1/%s/paper/%s?method=%s&flag=%s", bean.getSubject(), bean.getId(), bean.getMethod(), bean.getFlag());
		
		String token = authService.getToken(JingYouConstants.INTERFACE_TYPE_PAPER_DOWN, JingYouConstants.INTERFACE_LIMIT_PAPER_DOWN);
		
		return Utility.sendPut(token, url);
	}
	
	public XhPage<PaperDto> str2Xhpage(XhPage<PaperDto> page, JSONObject json) throws ParseException{
//		JSONObject json = JSON.parseObject(result);
		JSONArray array = json.getJSONArray("Data");
		List<PaperDto> list = array2ListPaper(array);
		page.setRecords(list);
		page.setTotal(json.getLongValue("Count"));
		return page;
	}
	
	private List<PaperDto> array2ListPaper(JSONArray arr) throws ParseException{
		List<PaperDto> list = new ArrayList<PaperDto>();
		for(int i=0;i<arr.size();i++){
			JSONObject json = arr.getJSONObject(i);
			list.add(json2Paper(json));
		}
		return list;
	}
	
	private PaperDto json2Paper(JSONObject json) throws ParseException{
		PaperDto p = new PaperDto();
		String paperID = json.getString("ID");
		p.setId(paperID);
		p.setQuestionCount(json.getInteger("QuesCount"));
		p.setTitle(json.getString("Title"));
		p.setTotalScore(json.getInteger("Score"));
		p.setSubjectId(json.getString("Subject"));
		p.setCreatorId(json.getString("CreatorID"));
		p.setCreateTime(DateUtils.parseDate(json.getString("CreateDate"), "yyyy-MM-dd'T'HH:mm:ss"));
		JSONArray array = json.getJSONArray("Groups");
		List<PaperChapterDto> paperCharpts = new ArrayList<PaperChapterDto>(array.size());
		for(int i=0;i<array.size();i++){
			JSONObject questionInfo = array.getJSONObject(i);
			String title = questionInfo.getString("Key");
			JSONArray questions = questionInfo.getJSONArray("Value");
			PaperChapterDto chapter = new PaperChapterDto();
			chapter.setPaperId(paperID);
			chapter.setQuestionCount(questions.size());
			chapter.setTitle(title);
			List<PaperQuestionDto> paperQuestionDtoList = new ArrayList<PaperQuestionDto>();
			chapter.setQuestions(paperQuestionDtoList);
			for(int j=0;j<questions.size();j++){
				JSONObject question = questions.getJSONObject(j);
				PaperQuestionDto paperQuestion = new PaperQuestionDto();
				paperQuestion.setOrderNo(j);
				paperQuestion.setPaperId(paperID);
				QuestionDto questionDto = questionService.jyQues2QuestionDto(question);
				paperQuestion.setQuestion(questionDto);
				paperQuestion.setQuestionId(paperQuestion.getId());
				paperQuestion.setScore(paperQuestion.getScore());
				paperQuestionDtoList.add(paperQuestion);
			}
			paperCharpts.add(chapter);
		}
		p.setPaperCharpts(paperCharpts);
		return p;
	}
	
	
}
